import { call, put, select, takeLatest } from 'redux-saga/effects';
function userSlice(state = [], actions) {
  const { type, payload } = actions;
  switch (type) {
    case 'ADD_USER': {
      return [...state, ...payload];
    }
    case 'DEL_USER': {
      return state.filter(item => item.id !== payload.id);
    }
    default:
      return state;
  }
}

export default userSlice;

const getUserListApi = () => {
  return new Promise(resolve => {
    setTimeout(() => {
      const list = Array.from({ length: 4 }, (item, index) => {
        return {
          id: index,
          name: `黄军泉${index}`,
        };
      });
      resolve(list);
    }, 2000);
  });
};

const delUserApi = () => {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve();
    }, 2000);
  });
};

function* getUserListSync() {
  const userList = yield call(getUserListApi);
  yield put({ type: 'ADD_USER', payload: userList });
}

function* delUserSync() {
  const userList = yield select(state => state.user);
  const [useJson] = userList || [];
  yield call(delUserApi);
  yield put({ type: 'DEL_USER', payload: useJson });
}

function* userSaga() {
  yield takeLatest('ADD_NAME_LIST_SYNC', getUserListSync);
  yield takeLatest('DEL_USER_SYNC', delUserSync);
}

export { userSaga };
